package com.fuyu.system.filter;

import com.fuyu.common.utils.JwtUtil;
import com.fuyu.system.action.Ipermission;
import com.fuyu.system.domain.SecurityUser;
import com.fuyu.system.domain.UserInfo;
import com.fuyu.system.utils.ResponseUtils;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private Ipermission ipermission;


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token = request.getHeader("Authorization");
        log.info("\ntoken: {}", token);
        String requestURI = request.getRequestURI();
        log.info("\n访问地址: {}", requestURI);

        if (!StringUtils.hasLength(token)) {
            filterChain.doFilter(request, response);
        } else {
            //这个else必须要有不然会重复判断,导致放行失败
            try {
                boolean verify = JwtUtil.verify(token);

                String userId = JwtUtil.getUserId(token);

                log.info("\ntoken检验成功");
                log.info("\n用户id:{}", userId);

                UserInfo userInfo = new UserInfo();

                //用户权限列表
                List<String> permissionList = ipermission.getPermissionList(userId);

                SecurityUser securityUser = new SecurityUser(userInfo, permissionList, null);

                Collection<? extends GrantedAuthority> authorities = securityUser.getAuthorities();

                UsernamePasswordAuthenticationToken authenticationToken =
                        new UsernamePasswordAuthenticationToken(userInfo, null, authorities);
                SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            } catch (Exception e) {
                log.error("\n异常:{}", e.getMessage());
                Map<String, Object> res = new HashMap<>();
                res.put("code", 401);
                res.put("msg", "认证异常");
                ResponseUtils.send(response, res);
            } finally {
                filterChain.doFilter(request, response);
            }

        }

    }
}
